﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web.Compilation;
using System.Web.Mvc;

namespace NetSurveillance.WebApp.Utilities
{
    public class PermissionHelper
    {
        public static IEnumerable<Type> GetAllControllerTypes()
        {
            ICollection assembilies = BuildManager.GetReferencedAssemblies();
            IEnumerable<Type> allTypes = Type.EmptyTypes;
            foreach (Assembly assembily in assembilies)
            {
                IEnumerable<Type> typesInAsm;
                try
                {
                    typesInAsm = assembily.GetTypes();
                }
                catch (ReflectionTypeLoadException ex)
                {
                    typesInAsm = ex.Types;
                }
                allTypes = allTypes.Concat(typesInAsm);
            }
            return allTypes.Where(IsControllerType);
        }

        public static IEnumerable<MethodInfo> GetAllActions(Type controllerType)
        {
            if (!IsControllerType(controllerType)) return Enumerable.Empty<MethodInfo>();
            IEnumerable<MethodInfo> allActions =
                controllerType.GetMethods(BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public)
                    .Where(IsValidActionMethod);
            return allActions;
        }

        internal static bool IsControllerType(Type t)
        {
            return
                t != null &&
                t.IsPublic &&
                t.Name.EndsWith("Controller", StringComparison.OrdinalIgnoreCase) &&
                !t.IsAbstract &&
                typeof(IController).IsAssignableFrom(t);
        }

        private static bool IsValidActionMethod(MethodInfo methodInfo)
        {
            if (!(methodInfo.IsSpecialName || methodInfo.GetCustomAttributes(typeof(NonActionAttribute), false).Any()))
            {
                var declaringType = methodInfo.GetBaseDefinition().DeclaringType;
                return !(declaringType != null && declaringType.IsAssignableFrom(typeof(Controller)));
            }
            return false;
        }

        internal static string ControllerDisplayName(string name)
        {
            if (string.IsNullOrEmpty(name) || !name.EndsWith("Controller", StringComparison.OrdinalIgnoreCase)) return name;
            return name.Substring(0, name.Length - "Controller".Length);
        }

        internal static string ControllerDisplayName(Type ctlType)
        {
            return ctlType == null ? string.Empty : ControllerDisplayName(ctlType.Name);
        }
    }
}